package com.example.controller;

import com.example.dto.UserDto;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceimpl;
import com.example.utils.DButil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String datetime = String.valueOf(LocalDateTime.now());
        String sql = "insert into userinfo(USERNAME, PASSWORD, DATATIME) values(?, ?, ?)";
        Connection conn = DButil.getConnection();
        UserService userService = new UserServiceimpl();
        UserDto userDto = userService.register(username, password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userDto.setUser(user);
        if (userDto.getMsg().equals("注册成功")){
            try {
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, password);
                ps.setString(3, datetime);
                ps.executeUpdate();
//                req.getSession().setAttribute("user", userDto.getUser());
                req.getRequestDispatcher("index.jsp").forward(req, resp);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } catch (ServletException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            req.setAttribute("Msg", userDto.getMsg());
//            System.out.println(userDto.getMsg());
            try {
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            } catch (ServletException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
